package main

import (
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/http"
)

type Result struct {
	Title  string `json:"title"`
	Author []struct {
		Name string `json:"name"`
	} `json:"author"`
	Logo        string `json:"logo"`
	Publisher   string `json:"publisher"`
	Published   string `json:"published"`
	Page        string `json:"page"`
	Price       string `json:"price"`
	Designed    string `json:"designed"`
	Description string `json:"description"`
}

func QueryIsbn(isbn string) ([]*BookItem, error) {
	if len(isbn) == 0 {
		return nil, errors.New("isbn 为空")
	}
	var isbnUrl = "https://www.98api.cn/api/isbn.php"
	req, err := http.NewRequest("GET", isbnUrl, nil)
	if err != nil {
		return nil, err
	}
	q := req.URL.Query()
	q.Add("isbn", isbn)
	req.URL.RawQuery = q.Encode()
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	resJsonStr, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}
	var resObj Result
	err = json.Unmarshal(resJsonStr, &resObj)
	if err != nil {
		return nil, err
	}
	var bookItem BookItem
	bookItem.Isbn = isbn
	bookItem.Count = 2
	bookItem.Title = resObj.Title
	if len(resObj.Author) > 0 {
		bookItem.AuthorName = resObj.Author[0].Name
	} else {
		bookItem.AuthorName = ""
	}
	bookItem.Logo = resObj.Logo
	bookItem.Publisher = resObj.Publisher
	bookItem.Published = resObj.Published
	bookItem.Page = resObj.Page
	bookItem.Price = resObj.Price
	bookItem.Designed = resObj.Designed
	bookItem.Description = resObj.Description
	return []*BookItem{&bookItem}, nil
}
